#include <iostream>
#include <cstdio>
#include <cstring>
#include <unistd.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <unistd.h>
#include <string>
#include <stdlib.h>
#include <arpa/inet.h>

#define MAX_SIZE 128
using std::cout;
using std::cerr;
using std::endl;

class UDP_client
{
    public:
    UDP_client(std::string Server_ip,int Server_port)
    :fd_(-1)
    ,Server_ip_(Server_ip)
    ,Server_port_(Server_port)
    {}


    ~UDP_client()
    {
        if(fd_ >=0)
        {
            close(fd_);
        }
    }

    bool Init_Client()
    {
        fd_=socket(AF_INET,SOCK_DGRAM,0);
        if(fd_ < 0)
        {
            perror("Client create socket failed\n");
            return false;
        }
        cout<<"Client create socket successed\n"<<endl;
        return true;
    }

    bool Start()
    {
        std::string msg="";
        struct sockaddr_in peer;
        peer.sin_family=AF_INET;
        peer.sin_port=htons(Server_port_);
        peer.sin_addr.s_addr=inet_addr(Server_ip_.c_str());
        char tmp_bar[MAX_SIZE];//有问题，为啥定义再循环体内部会有问题。
        while(1)
        {
             cout<<"Please Enter # ";
            sendto(fd_,msg.c_str(),sizeof(msg),0,(struct sockaddr*)&peer,sizeof(peer));
            getline(std::cin,msg);


            struct sockaddr_in tmp;
            socklen_t len=sizeof(tmp);
            ssize_t size=recvfrom(fd_,tmp_bar,sizeof(tmp_bar)-1,0,(struct sockaddr*)&tmp,&len);
            if(size > 0)
            {
                tmp_bar[MAX_SIZE-1]='\0';
                 cout<<"echo-message : "<<tmp_bar<<endl;
            }
            else
            {
                cout<<"Client recvfrom failed"<<endl;
            }
           
            
        }
    }
    private:
    int fd_;
    std::string Server_ip_;
    int Server_port_;
};